import React, { lazy, Suspense } from 'react';
import type { Menu } from '@/api/system';
import type { RouteObject } from 'react-router-dom';
import { Navigate } from 'react-router-dom';

// 动态加载组件
const loadComponent = (componentPath?: string) => {
  if (!componentPath) {
    return <Navigate to="/404" replace />;
  }

  // 清理组件路径，移除多余的 pages/ 前缀
  const cleanPath = componentPath.replace(/^pages\//, '');
  console.log('[loadComponent] 原始路径:', componentPath, '清理后路径:', cleanPath);

  // 返回一个动态加载的组件
  const LazyComponent = lazy(() => {
    return import(/* @vite-ignore */ `/src/pages/${cleanPath}`)
      .then(module => ({ default: module.default || module }))
      .catch(() => {
        // 组件加载失败时重定向到 404 页面
        console.error('[loadComponent] 组件加载失败:', `/src/pages/${cleanPath}`);
        return {
          default: () => <Navigate to="/404" replace />
        };
      });
  });

  return (
    <Suspense fallback={<div>Loading...</div>}>
      <LazyComponent />
    </Suspense>
  );
};

// 将菜单转换为路由配置
export const generateRoutes = (menus: Menu[]): RouteObject[] => {
  const routes: RouteObject[] = [];

  const generateRoute = (menu: Menu): RouteObject | null => {
    // 只处理菜单类型的路由
    if (menu.type !== 'C' || !menu.status || !menu.visible) {
      return null;
    }

    console.log('[generateRoutes] 生成路由:', {
      path: menu.path,
      component: menu.component,
      name: menu.name,
      type: menu.type
    });

    const route: RouteObject = {
      path: menu.path,
      element: loadComponent(menu.component),
    };

    // 添加路由元信息
    route.meta = {
      title: menu.name,
      icon: menu.icon,
      permission: menu.permission,
      breadcrumb: true,
      keepAlive: true,
    };

    return route;
  };

  // 递归生成路由
  const buildRoutes = (menuList: Menu[]) => {
    menuList.forEach(menu => {
      if (menu.type === 'M') {
        // 目录类型，递归处理子菜单
        if (menu.children) {
          buildRoutes(menu.children);
        }
      } else if (menu.type === 'C') {
        // 菜单类型，生成路由
        const route = generateRoute(menu);
        if (route) {
          routes.push(route);
        }
      }
    });
  };

  buildRoutes(menus);
  return routes;
};

// 生成扁平化的菜单列表（用于权限检查）
export const flattenMenus = (menus: Menu[]): Menu[] => {
  const result: Menu[] = [];

  const flatten = (menuList: Menu[]) => {
    menuList.forEach(menu => {
      result.push(menu);
      if (menu.children) {
        flatten(menu.children);
      }
    });
  };

  flatten(menus);
  return result;
};

// 检查用户是否有权限访问某个路由
export const hasRoutePermission = (
  route: RouteObject,
  permissions: string[]
): boolean => {
  const meta = route.meta as { permission?: string };
  if (!meta?.permission) {
    return true; // 没有权限要求的路由默认可以访问
  }

  return permissions.includes(meta.permission);
};

export default generateRoutes;